#include "mycanvas.h"
#include "spline.h"
#include "QMouseEvent"
#include <QVector2D>

MyCanvas::MyCanvas(QWidget *parent) :
        QWidget(parent)
{
    this->contador=0;
}

void MyCanvas::paintEvent(QPaintEvent* pEvent)
{
    this->Limpiar();
    this->pintarPuntos();
    if(this->contador>=2)
    {
        QListIterator<QVector2D> it(this->nodos);
        QVector2D val;
        while(it.hasNext())
        {
            val=it.next();
        }
        spLine s = spLine(this->nodos,this->contador-1);
        s.pintarFuncion(this);
    }
}

bool compararNodos(QVector2D nodo1, QVector2D nodo2)
{
    return nodo1.toPoint().x()<=nodo2.toPoint().x();
}

void MyCanvas::mousePressEvent(QMouseEvent * event)
{
    if(!existeAbscisa(event->x())){
        this->nodos << QVector2D(QPoint(event->x(), event->y()));
        qSort(this->nodos.begin(), this->nodos.end(), compararNodos);
        this->contador++;
        this->repaint();
    }
}

void MyCanvas::Limpiar()
{
    QPainter painter(this);
    QSize size = this->size();
    painter.fillRect(0,0,size.width(), size.height(), Qt::black);
}
void MyCanvas::pintarPuntos(){
    QPainter painter(this);
    painter.setPen(Qt::white);
    for (int i=0; i<this->contador;i++){
        painter.drawLine(this->nodos[i].toPoint().x()-1,this->nodos[i].toPoint().y()-1,this->nodos[i].toPoint().x()+1,this->nodos[i].toPoint().y()+1);
        painter.drawLine(this->nodos[i].toPoint().x()-1,this->nodos[i].toPoint().y()+1,this->nodos[i].toPoint().x()+1,this->nodos[i].toPoint().y()-1);
        qDebug("%d;%d", this->nodos[i].toPoint().x(), this->nodos[i].toPoint().y());
    }
    qDebug("****************************************************************");
}
bool MyCanvas::existeAbscisa(int x){
    for (int i=0; i<this->contador;i++){
        if (this->nodos[i].toPoint().x() == x)
            return true;
    }
    return false;
}
